<script setup lang="ts">
import { updateNodeAPI } from '@/apis/updateNode'
import { uploadImageAPI } from '@/apis/uploadImage'
import { useProjectConfigStore } from '@/store/projectConfig'
import { useUserInfoStore } from '@/store/userInfo'

// Assets
import modalSuccessIcon from '@/static/images/modal/success.png'
import { fetchProjectNodeListAPI } from '@/apis/fetchProjectNodeList'
import { fetchNodeListAPI } from '@/apis/fetchNodeList'
import { fetchProjectDetailAPI } from '@/apis/fetchProjectDetail'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const projectConfigStore = useProjectConfigStore()

// 表单组件 ref
const formRef = ref<any>(null)
// loading 状态
const loading = ref(false)
// 是否显示表单提交成功弹窗
const isShowSuccessModal = ref(false)

// 待获取的数据
const projectId = ref('')
const currentNode = ref<ProjectNode | null>(null)
const nodeList = ref<ProjectNode[]>([])

// 从路由参数中获取数据
onLoad(async (options) => {
  if (options && options.project_id) {
    loading.value = true

    projectId.value = options.project_id

    const projectRes = await fetchProjectDetailAPI(projectId.value, userInfoStore.userInfo!.token!)
    const project = projectRes.data?.data

    const rawListRes = await fetchNodeListAPI(
      project!.project_type_id!.toString(),
      userInfoStore.userInfo?.group_id?.toString(),
    )
    let rawList = rawListRes.data!.data!

    // 业务员的节点列表不应当包含第一项，因为第一项在项目创建时就有了
    if (userInfoStore.userInfo?.group_id?.toString() === '4')
      rawList = rawList.slice(1)

    currentNode.value = projectConfigStore.nodeLists[project!.project_type_id!.toString()].find(el => el.id?.toString() === project?.node_id?.toString())!

    // 请求节点数据
    const res = await fetchProjectNodeListAPI({
      project_id: projectId.value,
    }, userInfoStore.userInfo!.token!)
    if (res.data?.code === 1) {
      const activedList = res.data.data

      // 筛选节点列表，只剩下没上传过的节点
      function arrayDiff(arrA: ProjectNode[], arrB: ProjectNode[]) {
        const idsB = arrB.map(item => item.node_id?.toString())
        return arrA.filter(item => !idsB.includes(item.id?.toString()))
      }

      nodeList.value = arrayDiff(rawList, activedList)

      loading.value = false
    }
    else {
      uni.showToast({ title: res.data?.msg, icon: 'none' })

      loading.value = false
    }
  }
})

// 表单数据
const formData = ref({
  node_id: '',
  images: [] as string[],
  videos: [] as string[],
  videoThumbs: [] as string[],
  desc: '',
})

// 校验规则
const rules = {
  node_id: [
    { required: true, message: '项目节点不可为空' },
  ],
}

/* ---------------------------- SelectNode START ---------------------------- */
const selectedNodeIndex = ref<number | null>(null)

watch(selectedNodeIndex, (newVal) => {
  if (newVal && nodeList.value.length > 0) {
    const selectedNode = nodeList.value[newVal]
    formData.value.node_id = `${selectedNode.id}`
  }
})

const selectedNodeName = computed(() => {
  if (selectedNodeIndex.value && nodeList.value.length > 0) {
    const selectedNode = nodeList.value[selectedNodeIndex.value]
    return selectedNode.name
  }
})

function handleSelectNode(e: any) {
  selectedNodeIndex.value = e.detail.value
}
/* ----------------------------- SelectNode END ----------------------------- */

/* ---------------------------- ChooseImage START --------------------------- */
function handlePickImage() {
  uni.showActionSheet({
    itemList: ['拍摄', '从手机相册中选择'],
    success: (result) => {
      const sourceType = result.tapIndex === 0 ? 'camera' : 'album'
      uni.chooseMedia({
        count: 9,
        mediaType: ['image'],
        sourceType: [sourceType],
        sizeType: ['compressed'],
        success: (result) => {
          if (result.tempFiles.length > 0) {
            // 遍历照片临时路径的数组，将照片上传至服务器，将返回的 url 存入 formData
            result.tempFiles.forEach(async (path) => {
              const res = await uploadImageAPI(path.tempFilePath, userInfoStore.userInfo!.token!)
              if (res.data) {
                const resData = JSON.parse(res.data)
                if (resData.code === 1)
                  formData.value.images.push(resData.data.fullurl)
                else
                  uni.showToast({ title: resData.msg, icon: 'none' })
              }
              else {
                uni.showToast({ title: '上传图片失败', icon: 'none' })
              }
            })
          }
          else {
            uni.showToast({ title: '没有获取到照片', icon: 'none' })
          }
        },
      })
    },
  })
}

function handleDeleteImage(image: string) {
  formData.value.images = formData.value.images.filter(i => i !== image)
}
/* ----------------------------- ChooseImage END ---------------------------- */

/* ---------------------------- ChooseVideo START --------------------------- */
function handlePickVideo() {
  uni.showActionSheet({
    itemList: ['拍摄', '从手机相册中选择'],
    success: (result) => {
      const sourceType = result.tapIndex === 0 ? 'camera' : 'album'
      uni.chooseMedia({
        count: 9,
        mediaType: ['video'],
        sourceType: [sourceType],
        sizeType: ['compressed'],
        success: (result) => {
          if (result.tempFiles.length > 0) {
            // 遍历照片临时路径的数组，将照片上传至服务器，将返回的 url 存入 formData
            result.tempFiles.forEach(async (path) => {
              // 上传缩略图
              const thumbRes = await uploadImageAPI(path.thumbTempFilePath, userInfoStore.userInfo!.token!)
              if (thumbRes.data) {
                const thumbResData = JSON.parse(thumbRes.data)
                if (thumbResData.code === 1)
                  formData.value.videoThumbs.push(thumbResData.data.fullurl)
                else
                  uni.showToast({ title: thumbResData.msg, icon: 'none' })
              }
              // 上传视频
              const res = await uploadImageAPI(path.tempFilePath, userInfoStore.userInfo!.token!)
              if (res.data) {
                const resData = JSON.parse(res.data)
                if (resData.code === 1)
                  formData.value.videos.push(resData.data.fullurl)
                else
                  uni.showToast({ title: resData.msg, icon: 'none' })
              }
              else {
                uni.showToast({ title: '上传视频失败', icon: 'none' })
              }
            })
          }
          else {
            uni.showToast({ title: '没有获取到视频', icon: 'none' })
          }
        },
      })
    },
  })
}

function handleDeleteVideo(path: string) {
  formData.value.videos = formData.value.videos.filter(i => i !== path)
}
/* ----------------------------- ChooseVideo END ---------------------------- */

/* ------------------------------- 事件处理 START ------------------------------- */
const handleSubmit = useThrottleFn(() => {
  formRef.value.validate()
    .then(async () => {
      loading.value = true
      try {
        const res = await updateNodeAPI({
          project_id: projectId.value,
          node_id: formData.value.node_id,
          images: formData.value.images.join(','),
          video: formData.value.videos.join(','),
          video_image: formData.value.videoThumbs.join(','),
          desc: formData.value.desc,
        }, userInfoStore.userInfo!.token!)
        loading.value = false
        if (res.data?.code === 1)
          isShowSuccessModal.value = true
        else
          uni.showToast({ title: res.data?.msg, icon: 'none' })
      }
      catch (err) {
        loading.value = false
        uni.showToast({ title: '修改失败，请重试', icon: 'none' })
      }
    })
    .catch((errors: AnyObject[]) => {
      if (errors.length > 0)
        uni.showToast({ title: errors[0].message, icon: 'none' })
    })
}, 1000)

function handleExit() {
  router.back()
}
/* -------------------------------- 事件处理 END -------------------------------- */
</script>

<template>
  <view class="min-h-screen bg-#F8F8F8">
    <Spacer height="30" />
    <uv-form ref="formRef" :model="formData" :rules="rules">
      <view class="mx-30rpx bg-white rounded-10rpx">
        <ListCell label="当前节点">
          <ListValue>{{ currentNode ? currentNode.name : '未知' }}</ListValue>
        </ListCell>
        <Divider />
        <uv-form-item prop="node_id" :custom-style="{ padding: 0 }">
          <picker
            mode="selector" :value="selectedNodeIndex!" :range="nodeList.map((node) => node.name)"
            @change="handleSelectNode"
          >
            <ListCell label="修改节点">
              <ListLink :value="selectedNodeName" placeholder="请选择要修改的节点" />
            </ListCell>
          </picker>
        </uv-form-item>
        <Divider />
        <uv-form-item prop="images" :custom-style="{ padding: 0 }">
          <ListCell direction="column" label="上传照片（选填）">
            <PictureGrid
              mode="edit" :width="630" :cols="4" :pictures="formData.images" @pick-image="handlePickImage"
              @delete="(image) => handleDeleteImage(image)"
            />
          </ListCell>
        </uv-form-item>
        <Divider />
        <uv-form-item prop="videos" :custom-style="{ padding: 0 }">
          <ListCell direction="column" label="上传视频（选填）">
            <VideoGrid
              mode="edit" :width="630" :cols="4" :videos="formData.videos" :thumbs="formData.videoThumbs" @pick-image="handlePickVideo"
              @delete="(path) => handleDeleteVideo(path)"
            />
          </ListCell>
        </uv-form-item>
        <Divider />
        <uv-form-item prop="desc" :custom-style="{ padding: 0 }">
          <ListCell direction="column" label="节点备注（选填）">
            <textarea
              v-model="formData.desc"
              class="box-border w-full min-h-200rpx p-30rpx text-28rpx text-#333333 bg-#F0F0F0 rounded-10rpx"
              :maxlength="-1"
              placeholder="请输入节点备注信息"
              placeholder-style="color: #999999"
            />
          </ListCell>
        </uv-form-item>
      </view>
      <Spacer height="240" />
      <RGButton
        class="z-10 fixed bottom-80rpx x-center"
        @tap="handleSubmit"
      >
        确定提交
      </RGButton>
      <Spacer height="100" />
    </uv-form>
    <uv-overlay :show="isShowSuccessModal" @tap="handleExit">
      <uv-transition mode="zoom-in" :show="isShowSuccessModal">
        <view class="relative w-screen h-screen">
          <JZTModal
            :icon="modalSuccessIcon"
            title="修改成功"
            content="此项目的节点已经修改"
            button-label="确定"
            @confirm="handleExit"
          />
        </view>
      </uv-transition>
    </uv-overlay>
  </view>
  <uv-loading-page :loading="loading" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'updateProjectNode'
style:
  navigationBarTitleText: '修改项目节点'
layout: 'custom'
</route>
